//
//  ReplyViewController.m
//  MiaoTu
//
//  Created by dllo on 16/9/29.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ReplyViewController.h"
#import "UIView+Frame.h"
#import "Masonry.h"
#import "UIImageView+WebCache.h"
#import "ReplyTableCell.h"
#import "ZWYNetTool.h"
#import "ReplyModel.h"
#import "ReplyItem.h"
#import "SelfSizeTool.h"
#import "IQKeyboardManager.h"

#define kReplyTableCell @"ReplyTableCellIdentifier"

@interface ReplyViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *headImage;
@property (nonatomic, strong) UITextField *replyTextField;
@property (nonatomic, strong) NSMutableArray<ReplyItem *> *replyArray;
@end

@implementation ReplyViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.alpha = 0;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.alpha = 1;
}

- (void)loadView {
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = scrollView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeAll;
    
    UIImageView *backImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"replyBackImage"]];
    backImage.frame = CGRectMake(0, 64, self.view.dk_width, self.view.dk_height - 60 - 64);
    [self.view addSubview:backImage];
    
    [self setUpNavigationTabBar];
    [self createTableView];
    [self createReplyView];
    [self createData];
}

#pragma mark - View
- (void)setUpNavigationTabBar {
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationItem.title = @"评论";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:0.345 green:0.361 blue:0.369 alpha:1.000];
}

- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.dk_width, self.view.dk_height - 60 - 64) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerNib:[UINib nibWithNibName:@"ReplyTableCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kReplyTableCell];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor colorWithWhite:0.925 alpha:1.000];
}

- (void)createReplyView {
    UIView *replyView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.dk_height - 60, self.view.dk_width, 60)];
    [self.view addSubview:replyView];
//    replyView.backgroundColor = [UIColor greenColor];
    self.headImage = [UIImageView new];
    [replyView addSubview:_headImage];
    [_headImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.height.width.mas_equalTo(28);
        make.centerY.mas_equalTo(replyView);
    }];
    _headImage.layer.cornerRadius = 14;
    _headImage.layer.masksToBounds = YES;
    NSString *headUrl = [[NSUserDefaults standardUserDefaults] valueForKey:@"headUrl"];
    [_headImage sd_setImageWithURL:[NSURL URLWithString:headUrl]];
    
    UIButton *sendReplyButton = [UIButton new];
    [replyView addSubview:sendReplyButton];
    [sendReplyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(replyView.mas_right).offset(-10);
        make.centerY.mas_equalTo(replyView);
        make.width.height.mas_equalTo(_headImage);
    }];
    [sendReplyButton setImage:[UIImage imageNamed:@"sendReply"] forState:UIControlStateNormal];
    [sendReplyButton addTarget:self action:@selector(sendReply) forControlEvents:UIControlEventTouchUpInside];
    
    self.replyTextField = [UITextField new];
    [replyView addSubview:_replyTextField];
    [_replyTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_headImage.mas_right).offset(10);
        make.centerY.mas_equalTo(_headImage.mas_centerY);
        make.right.mas_equalTo(sendReplyButton.mas_left).offset(-10);
        make.height.mas_equalTo(replyView);
    }];
    _replyTextField.placeholder = @"在这里说点什么吧";
    _replyTextField.delegate = self;
}

#pragma mark - Data
- (void)createData {
    NSString *tocken = [[NSUserDefaults standardUserDefaults] objectForKey:@"tocken"];
    if (tocken.length == 0) {
        tocken = @"";
    }
    NSString *urlString = [NSString stringWithFormat:@"http://api.miaotu.net/v2/yueyou/reply?token=%@&yid=%@&page=1&num=10000", tocken, _yid];
    NSDictionary *headerDic = @{@"User-Agent":@"Dalvik/1.6.0 (Linux; U; Android 4.3; R6007 Build/JLS36C) Paros/3.2.13", @"Host":@"api.miaotu.net", @"Connection":@"Keep-Alive"};
    
    [ZWYNetTool GET:urlString andBody:nil andHeader:headerDic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        ReplyModel *replyModel = [ReplyModel modelWithDic:result];
        self.replyArray = replyModel.Items.mutableCopy;
        if (_replyArray.count == 0) {
            [_tableView removeFromSuperview];
        }
        [_tableView reloadData];
    } andFailureBlock:^(NSError *error) {
        
    }];
    
}

#pragma mark - TableView DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _replyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ReplyTableCell *cell = [tableView dequeueReusableCellWithIdentifier:kReplyTableCell forIndexPath:indexPath];
    cell.reply = _replyArray[indexPath.row];
    CGFloat width = self.tableView.dk_width - 58 - 30;
    CGFloat height = [SelfSizeTool selfSizeHeightWithString:_replyArray[indexPath.row].Content width:width font:[UIFont systemFontOfSize:17.f]];
    cell.replyLabelHeight.constant = height;
    cell.selectionStyle  = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = self.tableView.dk_width - 58 - 30;
    CGFloat height = [SelfSizeTool selfSizeHeightWithString:_replyArray[indexPath.row].Content width:width font:[UIFont systemFontOfSize:17.f]];
    return height + 70;
}

#error 写到这里了, 要动态计算键盘高度, 看一眼设计图
#pragma mark - TextField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    _tableView.frame = CGRectMake(0, 64, self.view.dk_width, 200);
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    _tableView.frame = CGRectMake(0, 64, self.view.dk_width, self.view.dk_height - 60 - 64);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField endEditing:YES];
    return YES;
}

#pragma mark - Action
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)sendReply {
    NSLog(@"sendReply");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
